var app = angular.module("app", ['ngRoute', 'ui.bootstrap', 'ui.select', 'ngSanitize', 'chart.js', 'toaster',
    /*productstart*/ "app.templates", /*productend*/
    'app.directives', 'app.login', 'app.knob', 'ja.qr', 'app.confirm', 'app.baseinfo', 'app.home', 'app.setting', 'app.event', 'app.order'
]);

app.factory('authInterceptor', ['$rootScope', '$q', '$location',
    function ($rootScope, $q, $location) {
        return {
            request: function (config) {
                //显示loading框
                $rootScope.loading = true;
                if (!$rootScope.requests) {
                    $rootScope.requests = 0;
                }
                $rootScope.requests++;
                var token = null;
                if (localStorage.rememberMe) {
                    token = localStorage.token;
                } else {
                    token = sessionStorage.token;
                }

                if (!token) {
                    localStorage.removeItem("token");
                    sessionStorage.removeItem("token");
                    window.location.href = "login.html";
                }
                config.headers = config.headers || {};
                config.headers["x-access-token"] = token;

                return config;
            },
            response: function (response) {
                $rootScope.requests--;
                if ($rootScope.requests < 1) {
                    //隐藏loading框
                    $rootScope.loading = false;
                }

                if (response.status === 401) {
                    // handle the case where the user is not authenticated
                    localStorage.removeItem("token");
                    sessionStorage.removeItem("token");
                    window.location.href = "login.html";
                }

                if (response.headers()['content-type'] === "application/json;charset=UTF-8") {
                    // Validate response, if not ok reject
                    var data = response.data;

                    if (!data) {
                        return $q.reject(response);
                    }

                    if (!data.success) {
                        response.errMsg = data.errMsg;
                        return $q.reject(response);
                    }
                }

                return response || $q.when(response);
            },
            responseError: function (response) {
                $rootScope.requests--;
                if ($rootScope.requests < 1) {
                    //隐藏loading框
                    $rootScope.loading = false;
                }

                if (response && response.status === 401) {
                    /* localStorage.removeItem("token");
                     sessionStorage.removeItem("token");
                     window.location.href = "login.html";*/
                    response.errMsg = "没有权限";
                    return $q.reject(response);
                } else {
                    response.errMsg = "发生未知错误！请检查网络连接或稍后再试";
                    return $q.reject(response);
                }
            }
        };
    }]);

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
}]);

app.config(["$routeProvider", function ($routeProvider) {
    $routeProvider.when("/", {
        redirectTo: "/home"
    }).when("/home", {
        templateUrl: "partials/home/home.html",
        controller: "homeCtrl"
    }).when("/login", {
        templateUrl: "login.html",
        controller: "loginCtrl"
    }).when("/setting", {
        templateUrl: "partials/setting/setting.html",
        controller: "settingCtrl"
    }).when("/baseinfo/userInfo", {
        templateUrl: "partials/baseinfo/user_list.html",
        controller: "userCtrl"
    }).when("/baseinfo/userInfo/scoreRecord/:userId", {
        templateUrl: "partials/baseinfo/score_record.html",
        controller: "scoreRecordCtrl"
    }).when("/baseinfo/userInfo/orderRecord/:userId", {
        templateUrl: "partials/baseinfo/order_record.html",
        controller: "orderRecordCtrl"
    }).when("/event/list", {
        templateUrl: "partials/event/event_list.html",
        controller: "eventCtrl"
    }).when("/order/list", {
        templateUrl: "partials/order/list.html",
        controller: "orderCtrl"
    }).otherwise({
        redirectTo: "/home"
    });
}]);


app.controller("headerCtrl", ['$rootScope', '$scope', '$modal', 'loginService',
    function ($rootScope, $scope, $modal, loginService) {
        loginService.getUser().then(function (user) {
            $rootScope.user = user;
            var token = loginService.getAccessToken();
        });

        $scope.logout = function () {
            localStorage.removeItem("token");
            sessionStorage.removeItem("token");
            window.location.href = "login.html";
        };

    }]);

app.directive("btnAuth", ['loginService', function (loginService) {
    return {
        restrict: "A",
        link: function (scope, element, attrs) {
            element.hide();
            var hasPermission = function (user, permission) {
                return true;
            };
        }
    }
}]);
